package com.awesome.common.util.device;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import com.awesome.common.base.mvp.BaseApplication;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import androidx.core.content.FileProvider;

/**
 * Author: JFangZ
 * Email: janezhang1901@163.com
 * Date: 2020/11/19 19:36
 * Description:App 相关工具类
 */
public class AppUtil {
    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/19 19:37
     * Description:获取应用包名
     */
    public static String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            return packageInfo.packageName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/19 19:37
     * Description:获取应用版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/19 19:37
     * Description:获取应用版本号
     */
    public static long getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                return packageInfo.getLongVersionCode();
            } else {
                return packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/19 19:37
     * Description:获取应用图标
     */
    public static Drawable getIcon(Context context) {
        try {
            PackageManager packageManager = context.getApplicationContext()
                    .getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(
                    context.getPackageName(), 0);
            return packageManager.getApplicationIcon(applicationInfo);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/19 19:37
     * Description:获取应用签名,可自己转为 md5,sha1,sha256 等
     */
    public static byte[] getSignature(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES);
                if (packageInfo.signingInfo == null) {
                    return null;
                }
                if (packageInfo.signingInfo.getApkContentsSigners() == null
                        || packageInfo.signingInfo.getApkContentsSigners().length == 0) {
                    return null;
                }
                return packageInfo.signingInfo.getApkContentsSigners()[0].toByteArray();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/19 19:37
     * Description:获取启动类全限定名
     */
    public static String getLaunchActivity(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setPackage(packageInfo.packageName);
            List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
            Iterator<ResolveInfo> iterator = resolveInfoList.iterator();
            if (iterator.hasNext()) {
                ResolveInfo resolveInfo = iterator.next();
                return resolveInfo.activityInfo.name;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/20 18:31
     * Description:安装应用
     */
    public static void install(Context context, File file, String authority) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!context.getPackageManager().canRequestPackageInstalls()) {
                //跳转到设置 - 允许安装未知来源 - 页面
                Uri packageURI = Uri.parse("package:" + context.getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                context.startActivity(intent);
                return;
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 赋予临时访问权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, authority, file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        } else {
            try {
                Runtime.getRuntime().exec("chmod 777 " + file.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/20 18:31
     * Description:卸载应用
     *
     * @param context
     * @param packageName 要卸载应用的包名
     */
    public static void uninstall(Context context, String packageName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + packageName));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * Author: JFangZ
     * Email:  janezhang1901@163.com
     * Date:2021/4/27 18:30
     * Description:获取应用ApplicationContext
     *
     * @return ApplicationContext
     */
    public static Application getApplication() {
        return BaseApplication.Companion.getInstance();
    }

    /**
     * Author: JFangZ
     * Email:  janezhang1901@163.com
     * Date:2021/4/27 18:30
     * Description:获取应用ID(包名)
     *
     * @return ApplicationId
     */
    public static String getApplicationId() {
        return getApplication().getPackageName();
    }

    /**
     * Author: JFangZ
     * Email:  janezhang1901@163.com
     * Date:2021/4/27 18:30
     * Description:是否是主进程
     *
     * @return true 是
     */
    public static boolean isMainProgress() {
        String processName = getProcessName(android.os.Process.myPid());
        if (processName != null) {
            //判断当前的进程是我们自己app
            //当前应用的初始化
            return processName.equals(getApplicationId());//自己的包名;
        }
        return false;
    }

    /**
     * Author: JFangZ
     * Email:  janezhang1901@163.com
     * Date:2021/4/27 18:30
     * Description:获取进程ID
     */
    public static String getProcessName(int pid) {
        ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2021/8/9 18:07
     * Description:判断应用是否在后台运行
     */
    public static boolean isBackground(Context context) throws Exception {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            throw new Exception("ActivityManager is null");
        }
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcessInfoList) {
            if (runningAppProcessInfo.processName.equals(context.getPackageName())) {
                return runningAppProcessInfo.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
            }
        }
        throw new Exception("Your app is running?");
    }
}
